package com.xckj.cycling.activity

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.text.TextUtils
import android.util.ArrayMap
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import androidx.core.view.children
import androidx.fragment.app.Fragment
import com.junca.android.base.CViewBinding
import com.xckj.cycling.framework.lazyGlobalViewModel
import com.tbruyelle.rxpermissions3.RxPermissions
import com.xckj.cycling.R
import com.xckj.cycling.databinding.ActivityMainBinding
import com.xckj.cycling.event.KeyboardEvent
import com.xckj.cycling.fragment.*
import com.xckj.cycling.framework.BaseActivityKt
import com.xckj.cycling.global.Constant
import com.xckj.cycling.service.BleConnService
import com.xckj.cycling.service.BluetoothMonitorReceiver
import com.xckj.cycling.service.FCMPushService
import com.xckj.cycling.utils.FacebookShareUtils
import com.xckj.cycling.utils.KeyboardHeightProvider
import com.xckj.cycling.viewmodel.MapViewModel
import org.greenrobot.eventbus.EventBus
import kotlin.system.exitProcess

/**选择车辆 https://d-qingxingapp.bigchun.com/#/chooseManagement
 * 个人信息  https://d-qingxingapp.bigchun.com/#/userInfo
 * 骑行历史  https://d-qingxingapp.bigchun.com/#/driveHistory
 * 健康推荐  https://d-qingxingapp.bigchun.com/#/helpRobot
 * 设置   https://d-qingxingapp.bigchun.com/#/setings
 *  排行榜 https://d-qingxingapp.bigchun.com/#/group
 *  勋章页面:     https://d-qingxingapp.bigchun.com/#/xunzhang
试骑页面：     https://d-qingxingapp.bigchun.com/#/tuijian
健康见解 页面 ：https://d-qingxingapp.bigchun.com/#/driveHealth
 * 骑行日历页面  ：  https://d-qingxingapp.bigchun.com/#/driveCalendar

1.语言切换  之前是原生的 现在变成h5了 需不需要暴漏一个方法  来传给你当前语言的状态。ios  getLangues({lang:'zh   或  en'})   anzhuo   getLangues(zh)
2.   链接服务里面  需要你们暴漏一个方法 用来打开 谷歌健康 （苹果健康） 的方法  getHealthServe
3. 健康见解  连接设备 方法  getManagementLink
4.  设置   自行车   点击  toDeviceLink
 * 主页
 */
class MainActivity : BaseActivityKt() {
    private var exitTime: Long = 0


    //每个tab对应的Fragment class
    private val fragmentClass: Array<Class<out Fragment>> = arrayOf(
        MineFragment::class.java,
        RouteLineFragment::class.java,
        MapFragment::class.java,
        RankFragment::class.java,
        CustomerServiceFragment::class.java
    )
    private var lastKey = ""
    private val fragments = ArrayMap<String, Fragment>()
    private var currentTab = -1
    private var bleListenerReceiver: BluetoothMonitorReceiver? = null

    @CViewBinding
    lateinit var viewBinding: ActivityMainBinding

    @SuppressLint("SetJavaScriptEnabled")
    override fun initView(root: View, savedInstanceState: Bundle?) {
        super.initView(root, savedInstanceState)
        FCMPushService.init()
        viewBinding.cacheWebview.loadUrl(Constant.WEB_URL + "setings")
        // 开启自定义蓝牙服务
        startService(Intent(this, BleConnService::class.java));
        bleListenerReceiver = BluetoothMonitorReceiver()
        val intentFilter = IntentFilter()
        // 监视蓝牙关闭和打开的状态
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        // 监视蓝牙设备与APP连接的状态
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
        registerReceiver(bleListenerReceiver, intentFilter)

        checkHealth()
        loginViewModel.unreadLiveData.observe(this) {
            if ((it?.is_read ?: 0) > 0) {
                viewBinding.unread4.visibility = View.VISIBLE
            } else {
                viewBinding.unread4.visibility = View.GONE
            }
        }
        viewBinding.tabbar.children.forEachIndexed { index, view ->
            view.setOnClickListener {
                if (index == 2 || index == 1 || index == 3) {
                    checkPermissionAndToMap(index)
                } else {
                    setCurrentTab(index)
                }
            }
        }
        setCurrentTab(0) //默认选中我的
    }

    lateinit var keyboardHeightProvider: KeyboardHeightProvider;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        handleIntent(intent)
        keyboardHeightProvider = KeyboardHeightProvider(this, window.decorView)
        window.decorView.post {
            keyboardHeightProvider.start()
        }
    }

    override fun onResume() {
        super.onResume()
        keyboardHeightProvider.setKeyboardHeightObserver { height, orientation ->
            EventBus.getDefault().post(KeyboardEvent(height))
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        handleIntent(intent)
        intent?.getIntExtra("index", 0)?.let {
            checkPermissionAndToMap(it)//说明是要骑行到终点
        }
    }

    private fun handleIntent(intent: Intent?) {
        intent ?: return
        intent.getStringExtra("share")?.let {
            val url = intent.getStringArrayListExtra("share_url")
            url?.let {
                FacebookShareUtils.shareImages(this, it.toTypedArray())
            }
        }
    }

    private val mapViewModel: MapViewModel by lazyGlobalViewModel()
    private fun checkPermissionAndToMap(index: Int) {
        RxPermissions(this).requestEachCombined(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ).subscribe {
            if (it.granted) {
                mapViewModel.refreshLocation()
                setCurrentTab(index)
            }
        }
    }

    override fun onPause() {
        super.onPause()
        keyboardHeightProvider.setKeyboardHeightObserver(null)
    }

    override fun onDestroy() {
        super.onDestroy()
        keyboardHeightProvider.close()
        unregisterReceiver(bleListenerReceiver)
    }

    /**
     * 设置当前效果
     */
    fun setCurrentTab(current: Int) {
//        if (current == 2) {
////            startActivity(Intent(this, WhereYouGoActivity::class.java))
//            return
//        }
        if (current == currentTab) {
            return
        }
        currentTab = current
        //选中效果
        viewBinding.tabbar.children.forEachIndexed { index, view ->
            view.isSelected = index == current
        }
        val clz = fragmentClass[current]
        val key = clz.name + "_$current"
        val fragment = fragments[key]
        val currentFragment = if (!TextUtils.isEmpty(lastKey)) {
            fragments[lastKey]
        } else null
        lastKey = key
        if (fragment != null) {
            supportFragmentManager.beginTransaction().apply {
                if (currentFragment != null) {
                    hide(currentFragment)
                }
            }.show(fragment).commitAllowingStateLoss()
        } else {
            val f = Fragment.instantiate(this, clz.name, onCreateFragmentArguments(current))
            supportFragmentManager.beginTransaction().apply {
                if (currentFragment != null) {
                    hide(currentFragment)
                }
            }.add(R.id.content, f).commitAllowingStateLoss()
            fragments[key] = f
        }
    }

    /**
     * 给fragment构建参数
     */
    private fun onCreateFragmentArguments(index: Int): Bundle? {
        //TODO 根据index 返回不同参数
        if (index == 3) {
            return Bundle().apply {
                putString("url", Constant.WEB_URL + "group")
            }
        }
        return null
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) {
            exit()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun exit() {
        if (System.currentTimeMillis() - exitTime > Constant.EXIT_TIME) {
            Toast.makeText(this@MainActivity, getString(R.string.back), Toast.LENGTH_SHORT).show()
            exitTime = System.currentTimeMillis()
        } else {
            finish()
            exitProcess(0)
        }
    }

    companion object {
        @JvmStatic
        @JvmOverloads
        fun toMain(
            context: Context,
            index: Int = 0,
            shareFacebook: String? = null,
            shareUrl: List<String>? = null
        ) {

            Intent(context, MainActivity::class.java).putExtra("index", index)
                .putExtra("share", shareFacebook)
                .apply {
                    if (shareUrl != null) {
                        putStringArrayListExtra("share_url", ArrayList(shareUrl))
                    }
                }
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP).apply {
                    context.startActivity(this)
                }
        }
    }
}